package com.xiong.wuliao.util;

import com.xiong.wuliao.entity.Goods;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/5.
 */
public class GoodsJSON {
    //private static Goods goods;
    //private static List<Goods> goodsList = new ArrayList<>();

    public static List<Goods> saveGoodsData(String s) {
        List<Goods> goodsList = new ArrayList<>();
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(s.trim());
            JSONObject object = jsonObject.optJSONObject("data");

            JSONArray array = object.optJSONArray("items");
            for (int index = 0; index < array.length(); index++) {
                JSONObject object1 = array.optJSONObject(index);
                Goods goods = new Goods();
                JSONObject obj = object1.optJSONObject("data");

                goods.setBrand_id(obj.optString("brand_id"));
                goods.setBrand_order(obj.optString("brand_order"));
                goods.setCategory_id(obj.optString("category_id"));
                goods.setCover_image_url(obj.optString("cover_image_url"));
                goods.setCreated_at(obj.optString("created_at"));
                goods.setDescription(obj.optString("description"));
                goods.setEditor_id(obj.optString("editor_id"));
                goods.setFavorites_count(obj.optString("favorites_count"));
                goods.setId(obj.optString("id"));

                JSONArray array1 = obj.getJSONArray("image_urls");
                List<String> list;
                if (array1 != null) {
                    list = new ArrayList<>();
                    for (int i = 0; i < array1.length(); i++) {
                        list.add(array1.optString(i));
                    }
                    goods.setImage_urls(list);
                }

                goods.setIs_favorite(obj.optBoolean("is_favorite"));
                goods.setName(obj.optString("name"));
                goods.setPrice(obj.optString("price"));
                goods.setPurchase_id(obj.optString("purchase_id"));
                goods.setPurchase_url(obj.optString("purchase_url"));
                goods.setSubcategory_id(obj.optString("subcategory_id"));
                goods.setUpdated_at(obj.optString("updated_at"));
                goods.setUrl(obj.optString("url"));

                goodsList.add(goods);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
        return goodsList;
    }
}
